package com.smasher.net.http

import android.util.Log
import com.smasher.net.help.TokenManager
import com.smasher.net.http.authorization.AuthorizationStrategy
import com.smasher.net.http.authorization.BearerTokenStrategy
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route

abstract class LoongAuthenticator : Authenticator {

    // 引入 AuthorizationStrategy 接口
    private var authorizationStrategy: AuthorizationStrategy = BearerTokenStrategy()

    override fun authenticate(route: Route?, response: Response): Request? {
        val authorization = response.request.header("Authorization")
        Log.i(TAG, "authenticate old: $authorization")
        val token = TokenManager.instance.getToken() ?: ""
        // 第3次认证失败返回null
        if (responseCount(response) >= 3) {
            println("认证失败，返回null")
            return null // If we've failed 5 times, give up.
        }

        return response.request.newBuilder()
            .header(
                authorizationStrategy.getAuthorizationHeaderName(),
                authorizationStrategy.getAuthorizationHeader(token)
            )
            .build()
    }


    private fun responseCount(response: Response): Int {
        var result = 1
        var currentResponse: Response? = response.priorResponse
        while (currentResponse != null) {
            result++
            currentResponse = currentResponse.priorResponse
        }
        return result
    }

    // 提供一个方法来设置当前的授权策略
    fun setAuthorizationStrategy(strategy: AuthorizationStrategy) {
        this.authorizationStrategy = strategy
    }

    companion object {
        const val TAG = "LoongAuthenticator"
    }
}